package com.magicsoft.share.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.magicsoft.share.constant.AppConstants;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

/**
 * @Author hwg
 * @Description：
 * @Date 2018/3/25
 */
public class WxShareUtil {

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Bundle bundle = msg.getData();
            int shareType = bundle.getInt("shareType");
            String title = bundle.getString("title");
            String shareUrl = bundle.getString("shareUrl");
            byte[] imageByte = bundle.getByteArray("imageByte");

            WXWebpageObject wxWebpageObject = new WXWebpageObject();
            wxWebpageObject.webpageUrl = shareUrl;

            WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
            wxMediaMessage.title = title;
            wxMediaMessage.thumbData = imageByte;

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = wxMediaMessage;

            if (shareType == 0) {
                req.scene = SendMessageToWX.Req.WXSceneSession;
            } else {
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
            }

            api.sendReq(req);

        }
    };

    public WxShareUtil() {

    }

    private static WxShareUtil instance;
    public IWXAPI api;

    public static WxShareUtil getInstance() {
        synchronized (WxShareUtil.class) {
            if (instance == null) {
                instance = new WxShareUtil();
            }
        }
        return instance;
    }

    /**
     * 初始化分享功能
     *
     * @param context
     */
    public WxShareUtil init(Context context) {
        api = WXAPIFactory.createWXAPI(context, AppConstants.WX_APP_ID, true);
        api.registerApp(AppConstants.WX_APP_ID);//将应用appid注册到微信
        return this;

    }

    /**
     * 分享给微信好友
     *
     * @param shareUrl
     * @param title
     */
    public void sendToWxFriend(final String shareUrl, final String title, final String imageUrl) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                Bitmap bitmap = getLocalOrNetBitmap(imageUrl);
                byte[] datas = bmpToByteArray(bitmap, 32);
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putInt("shareType", 0);
                bundle.putString("shareUrl", shareUrl);
                bundle.putString("title", title);
                bundle.putByteArray("imageByte", datas);
                msg.setData(bundle);
                mHandler.sendMessage(msg);


            }
        }).start();

//        WXWebpageObject wxWebpageObject = new WXWebpageObject();
//        wxWebpageObject.webpageUrl = shareUrl;
//
//        WXMediaMessage msg = new WXMediaMessage(wxWebpageObject);
//        msg.title = title;
//        msg.description = "I have a dream";
//
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = String.valueOf(System.currentTimeMillis());
//        req.message = msg;
//        req.scene = SendMessageToWX.Req.WXSceneSession;
//
//        api.sendReq(req);
    }


    /**
     * 分享给微信好友
     *
     * @param shareUrl
     * @param title
     */
    public void sendToWxFriend(final String shareUrl, final String title, final Bitmap imageUrl) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] datas = bmpToByteArray(imageUrl, 32);
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putInt("shareType", 0);
                bundle.putString("shareUrl", shareUrl);
                bundle.putString("title", title);
                bundle.putByteArray("imageByte", datas);
                msg.setData(bundle);
                mHandler.sendMessage(msg);

            }
        }).start();
    }


    /**
     * 分享到微信朋友圈
     *
     * @param shareUrl
     * @param title
     */
    public void sendToFriendCircle(final String shareUrl, final String title, final Bitmap imageUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] datas = bmpToByteArray(imageUrl, 32);

                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putInt("shareType", 1);
                bundle.putString("shareUrl", shareUrl);
                bundle.putString("title", title);
                bundle.putByteArray("imageByte", datas);
                msg.setData(bundle);
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    /**
     * 分享到微信朋友圈
     *
     * @param shareUrl
     * @param title
     */
    public void sendToFriendCircle(final String shareUrl, final String title, final String imageUrl) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                Bitmap bitmap = getLocalOrNetBitmap(imageUrl);
                byte[] datas = bmpToByteArray(bitmap, 32);

                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putInt("shareType", 1);
                bundle.putString("shareUrl", shareUrl);
                bundle.putString("title", title);
                bundle.putByteArray("imageByte", datas);
                msg.setData(bundle);
                mHandler.sendMessage(msg);

            }
        }).start();

//        WXWebpageObject wxWebpageObject = new WXWebpageObject();
//        wxWebpageObject.webpageUrl = shareUrl;
//
//        WXMediaMessage msg = new WXMediaMessage(wxWebpageObject);
//        msg.title = title;
//        msg.description = "I have a dream";
//
//        Bitmap bitmap = getLocalOrNetBitmap(imageUrl);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//        byte[] datas = baos.toByteArray();
//        msg.thumbData = datas;
//
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = String.valueOf(System.currentTimeMillis());
//        req.message = msg;
//        req.scene = SendMessageToWX.Req.WXSceneTimeline;
//
//        api.sendReq(req);

    }


    /**
     * 把网络资源图片转化成bitmap
     *
     * @param url 网络资源图片
     * @return Bitmap
     */
    public static Bitmap getLocalOrNetBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new URL(url).openStream(), 1024);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, 1024);
            copy(in, out);
            out.flush();
            byte[] data = dataStream.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            data = null;
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    private byte[] bmpToByteArray(Bitmap bit, int quality) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        int options = quality;
        while (baos.toByteArray().length > 32768 && options > 3) {
            baos.reset(); //清空output
            bit.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到output中
            options -= 2;
            Log.i("kkk", "" + baos.toByteArray().length);
        }
        return baos.toByteArray();

    }
}